#Python's arbitrary arguments in functions
In Python, the number of actual arguments passed to a function can be flexible. For example, the built-in function print
can accept any number of arguments.
There are two kinds of variable-length arguments in Python: arbitrary positional arguments and arbitrary keyword arguments.
# Arbitrary positional arguments
def func(*args):
pass
# Arbitrary keyword arguments
def func(**kwargs):
pass
#Arbitrary Positional Arguments
These allow a function to accept any number of positional arguments, which are collected into a tuple named args
:
def func(*args):
print(args)
func(1, 2, 3)
func(1, 2, 3, 4, 5)
Output:
(1, 2, 3) (1, 2, 3, 4, 5)
#Arbitrary Keyword Arguments
These allow a function to accept any number of keyword arguments, which are collected into a dictionary named kwargs
:
def func(**kwargs):
print(kwargs)
func(name='Tom', age=8, species='cat')
func(name='Jerry', age=6, species='mouse')
Output:
{'name': 'Tom', 'age': 8, 'species': 'cat'} {'name': 'Jerry', 'age': 6, 'species': 'mouse'}
#Combining Them
You can combine normal parameters, arbitrary positional arguments, and arbitrary keyword arguments in one function. The order must be: normal parameters, then *args
, then **kwargs
:
def func(arg1, arg2, *args, **kwargs):
pass
Here, the first two arguments go to arg1
and arg2
, any additional positional arguments go to args
, and all keyword arguments go to kwargs
.
#Argument Forwarding
You can accept arbitrary arguments with *args
and **kwargs
, then forward them to another function using unpacking syntax:
def my_print(*args, **kwargs):
print(*args, **kwargs) # Unpack arguments
my_print('Hello', end=',')
my_print('World')